package com.tencent.sr.iris.activity.service.activity.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tencent.sr.iris.activity.common.enums.ActivityStatusEnum;
import com.tencent.sr.iris.activity.common.enums.ActivityTaskStatusEnum;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityDTO;
import com.tencent.sr.iris.activity.interfaces.request.acticity.ActivityAndTaskRequest;
import com.tencent.sr.iris.activity.interfaces.response.activity.ActivityAndTaskResponse;
import com.tencent.sr.iris.activity.repository.entity.TIrisActivityDO;
import com.tencent.sr.iris.activity.repository.entity.TIrisActivityTaskDO;
import com.tencent.sr.iris.activity.repository.singlemapper.TIrisActivityMapper;
import com.tencent.sr.iris.activity.repository.singlemapper.TIrisActivityTaskMapper;
import com.tencent.sr.iris.activity.repository.singlemapper.example.TIrisActivityExample;
import com.tencent.sr.iris.activity.repository.singlemapper.example.TIrisActivityTaskExample;
import com.tencent.sr.iris.activity.service.activity.IrisActivityService;
import com.tencent.sr.iris.activity.service.constant.ActivityRedisKey;
import com.tencent.sr.iris.activity.service.util.BeanConvertUtil;
import com.tencent.sr.rmall.springbootstarter.redis.RedisClient;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class IrisActivityServiceImpl implements IrisActivityService {

    @Resource
    private TIrisActivityMapper activityMapper;

    @Resource
    private RedisClient redisClient;

    @Resource
    private TIrisActivityTaskMapper activityTaskMapper;

    @Override
    public List<TIrisActivityDO> getActivityByIds(List<String> idList) {

        List<String> keys = idList.stream()
                .map(i -> String.format(ActivityRedisKey.ACTIVITY_CACHE_KEY, i))
                .collect(Collectors.toList());
        List<String> retryKeys = Lists.newArrayList();

        List<String> caches = redisClient.mget(keys.toArray(new String[keys.size()]));

        for (int i = 0; i < caches.size(); i++) {
            String cache = caches.get(i);
            if (StrUtil.isBlank(cache)) {
                retryKeys.add(keys.get(i));
            }
        }

        if (CollectionUtil.isEmpty(retryKeys)) {
            return caches.stream()
                    .map(i -> JSON.parseObject(i, TIrisActivityDO.class))
                    .collect(Collectors.toList());
        }

        //查数据库
        TIrisActivityExample example = new TIrisActivityExample();
        example.createCriteria()
                .andPropertyIn(TIrisActivityTaskExample.ID, idList);
        List<TIrisActivityDO> list = activityMapper.selectByExample(example);
        if (CollectionUtil.isNotEmpty(list)) {
            //todo 设置缓存 删除缓存
            list.forEach(i -> redisClient.setex(String.format(ActivityRedisKey.ACTIVITY_CACHE_KEY,
                    i.getId()), JSON.toJSONString(i), 1000));
        }

        //重新查询
        caches = redisClient.mget(keys.toArray(new String[keys.size()]));
        return caches.stream().filter(i -> StrUtil.isNotBlank(i))
                .map(i -> JSON.parseObject(i, TIrisActivityDO.class))
                .collect(Collectors.toList());
    }

    @Override
    public ActivityDTO getActivity(String bizId) {
        //查询活动信息
        TIrisActivityExample activityExample = new TIrisActivityExample();
        activityExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityExample.BIZ_ID, bizId)
                .andPropertyEqualTo(TIrisActivityTaskExample.STATUS, ActivityStatusEnum.PROGRESSING.getCode());
        List<TIrisActivityDO> activityDOList = activityMapper.selectByExample(activityExample);
        if (CollectionUtils.isEmpty(activityDOList)) {
            return null;
        }
        ActivityDTO activityDTO = BeanConvertUtil.INSTANCE.convertActivityDO2DTO(activityDOList.get(0));
        TIrisActivityTaskExample taskExample = new TIrisActivityTaskExample();
        taskExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityTaskExample.ACTIVITY_ID, bizId)
                .andPropertyEqualTo(TIrisActivityTaskExample.STATUS, ActivityTaskStatusEnum.NORMAL.getCode());
        List<TIrisActivityTaskDO> activityTaskDOS = activityTaskMapper.selectByExample(taskExample);
        activityDTO.setActivityTaskDTOS(BeanConvertUtil.INSTANCE.convertActivityTaskDO2DTOList(activityTaskDOS));
        return activityDTO;
    }

    @Override
    public ActivityDTO getActivityAllTask(String bizId) {
        //查询活动信息
        TIrisActivityExample activityExample = new TIrisActivityExample();
        activityExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityExample.BIZ_ID, bizId)
                .andPropertyEqualTo(TIrisActivityTaskExample.STATUS, ActivityStatusEnum.PROGRESSING.getCode());
        List<TIrisActivityDO> activityDOList = activityMapper.selectByExample(activityExample);
        if (CollectionUtils.isEmpty(activityDOList)) {
            return null;
        }
        ActivityDTO activityDTO = BeanConvertUtil.INSTANCE.convertActivityDO2DTO(activityDOList.get(0));
        TIrisActivityTaskExample taskExample = new TIrisActivityTaskExample();
        taskExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityTaskExample.ACTIVITY_ID, bizId);
        List<TIrisActivityTaskDO> activityTaskDOS = activityTaskMapper.selectByExample(taskExample);
        activityDTO.setActivityTaskDTOS(BeanConvertUtil.INSTANCE.convertActivityTaskDO2DTOList(activityTaskDOS));
        return activityDTO;
    }

    @Override
    public ActivityAndTaskResponse getActivityAndTask(ActivityAndTaskRequest request) {
        log.info("getActivityAndTask通过activityId和taskId获取任务和子任务,request:{}", JSONObject.toJSONString(request));
        //查询活动信息
        TIrisActivityExample activityExample = new TIrisActivityExample();
        activityExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityExample.BIZ_ID, request.getActivityId())
                .andPropertyEqualTo(TIrisActivityTaskExample.STATUS, ActivityStatusEnum.PROGRESSING.getCode());
        List<TIrisActivityDO> activityDOList = activityMapper.selectByExample(activityExample);
        log.info("getActivityAndTask通过activityId和taskId获取任务和子任务,得到活动数据,request:{},activityDOList:{}",
                JSONObject.toJSONString(request), JSONObject.toJSONString(activityDOList));
        if (CollectionUtils.isEmpty(activityDOList)) {
            return null;
        }
        ActivityAndTaskResponse activityAndTaskResponse = BeanConvertUtil.INSTANCE
                .convertActivityDO2Response(activityDOList.get(0));
        TIrisActivityTaskExample taskExample = new TIrisActivityTaskExample();
        taskExample.createCriteria()
                .andPropertyEqualTo(TIrisActivityTaskExample.BIZ_ID, request.getTaskId())
                .andPropertyEqualTo(TIrisActivityTaskExample.ACTIVITY_ID, request.getActivityId())
                .andPropertyEqualTo(TIrisActivityTaskExample.STATUS, ActivityTaskStatusEnum.NORMAL.getCode());
        List<TIrisActivityTaskDO> activityTaskDOS = activityTaskMapper.selectByExample(taskExample);
        log.info("getActivityAndTask通过activityId和taskId获取任务和子任务,得到子任务数据,request:{},activityTaskDOS:{}",
                JSONObject.toJSONString(request), JSONObject.toJSONString(activityTaskDOS));
        if (CollectionUtil.isNotEmpty(activityTaskDOS)) {
            activityAndTaskResponse
                    .setTaskResponse(BeanConvertUtil.INSTANCE.convertTaskDO2TaskResponse(activityTaskDOS.get(0)));
        }
        log.info("getActivityAndTask通过activityId和taskId获取任务和子任务,完成查询,request:{},activityAndTaskResponse:{}",
                JSONObject.toJSONString(request), JSONObject.toJSONString(activityAndTaskResponse));
        return activityAndTaskResponse;
    }
}
